package com.hitemole.controller;

import java.io.IOException;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.hitemole.manager.MenuManager;
import com.hitemole.manager.MenuManager.CONNECTION_STATE;
import com.hitemole.network.ClientGame;
import com.hitemole.network.Network.ClientInfo;
import com.hitemole.network.ServerGame;

public class MenuController {

	private MenuManager manager;
	// private String[] server;
	private float refreshList = 5;

	public MenuController(MenuManager manager) {
		// TODO Auto-generated constructor stub
		this.manager = manager;
	}

	public void update(float delta) {
		// TODO Auto-generated method stub
		manager.getStage().act(delta);
		switch (manager.getState()) {
		case NOTHING:
			break;
		case CLIENTCONNECTED:
			manager.getGameCore().setScreen(
					manager.getGameCore().getGameServerScreen());
			break;
		case SERVERCONNECTED:
			ClientInfo cInfo = new ClientInfo();
			cInfo.height = Gdx.graphics.getHeight();
			cInfo.width = Gdx.graphics.getWidth();
			ClientGame.clientGame.sendToServer(cInfo);
			manager.getGameCore().setScreen(
					manager.getGameCore().getGameClientScreen());
			break;
		case STARTCLIENT:
			ClientGame.clientGame.createNewClient();
			manager.setState(CONNECTION_STATE.WAITSERVER);
			break;
		case STARTSERVER:
			try {
				ServerGame.serverGame.createNewServer();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			manager.setState(CONNECTION_STATE.WAITCLIENT);
			break;
		case WAITCLIENT:
			if (manager.getWaitingLabel().getColor().a <= 0)
				manager.getWaitingLabel().addAction(Actions.fadeIn(0));
			if (manager.getWaitingLabel().getColor().a >= 1)
				manager.getWaitingLabel().addAction(
						Actions.sequence(Actions.delay(1.8f),
								Actions.fadeOut(0.5f)));
			if (ServerGame.serverGame.isClientConnected())
				manager.setState(CONNECTION_STATE.CLIENTCONNECTED);
			break;
		case WAITSERVER:
			refreshList -= delta;
			if (refreshList <= 0) {
				ClientGame.clientGame.discoverHost();
				refreshList = 5;
				String[] server = {};
				if (ClientGame.clientGame.getServerList() != 0) {
					server = new String[ClientGame.clientGame.getServerList()];
					for (int i = 0; i < server.length; i++) {
						server[i] = "Server " + (i + 1);
					}
				}
				manager.setServerList(server);
			}
			if (ClientGame.clientGame.isConnected())
				manager.setState(CONNECTION_STATE.SERVERCONNECTED);
			break;
		default:
			break;

		}
	}

}
